package com.wulinbus.controller;

import org.apache.http.client.utils.URLEncodedUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fancy.common.security.MD5;
import com.fancy.common.utils.DateUtil;
import com.fancy.common.utils.StringUtil;
import com.wulinbus.model.CreativeModel;
import com.wulinbus.model.CreativeOrderModel;
import com.wulinbus.model.ScriptModel;
import com.wulinbus.model.ScriptOwnModel;
import com.wulinbus.model.UserCashLogModel;
import com.wulinbus.model.UserModel;
import com.wulinbus.service.CreativeOrderService;
import com.wulinbus.service.CreativeService;
import com.wulinbus.service.ScriptService;
import com.wulinbus.service.UserCashLogService;
import com.wulinbus.service.UserService;
import com.wulinbus.utils.CasUtil;

@Controller
@RequestMapping("/user")
public class UserController{

	@Resource
	private UserService userService;

	@Resource
	private ScriptService scriptService;

	@Resource
	private CreativeService creativeService;
	
	@Resource
	private CreativeOrderService creativeOrderService;
	
	@Resource
	private UserCashLogService userCashLogService;
	
	@RequestMapping("/user_info.html")
	public String user_info(Model model, HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			model.addAttribute("user", userModel);
			return "page-user-info";
		}
	}
	
	@RequestMapping(value = "editPsw.json", method = { RequestMethod.POST })
	public void editPsw(Model model,HttpServletRequest request,@RequestParam("old_pwd")String old_pwd,@RequestParam("pwd1")String new_pwd,HttpServletResponse response) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			response.getWriter().print("{\"message\":\"请先登录\",\"statusCode\":\"300\"}");
		}
		else
		{
			UserModel user = userService.findUserByUid(Integer.parseInt(uid));
			if(user != null && user.getPwd().equals(MD5.md5(old_pwd))){
				user.setPwd(MD5.md5(new_pwd));
				if(userService.updateUser(user) > 0)
					response.getWriter().print("{\"message\":\"操作成功\",\"statusCode\":\"200\",\"refresh\":\"true\"}");
				else
					response.getWriter().print("{\"message\":\"操作失败\",\"statusCode\":\"300\"}");
			}else{
				response.getWriter().print("{\"message\":\"您输入的密码不正确\",\"statusCode\":\"300\"}");
			}
		}
	}
	
	@RequestMapping(value = "editInfo.json", method = { RequestMethod.POST })
	public void editInfo(Model model,UserModel user, HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			response.getWriter().print("{\"message\":\"请先登录\",\"statusCode\":\"300\"}");
		}
		else
		{
			user.setUid(Integer.parseInt(uid));
			if(userService.updateUser(user) > 0)
				response.getWriter().print("{\"message\":\"操作成功\",\"statusCode\":\"200\",\"refresh\":\"true\"}");
			else
				response.getWriter().print("{\"message\":\"操作失败\",\"statusCode\":\"300\"}");
		}
	}
	
//	/**
//	 * 用户个人创意主页
//	 */
//	@RequestMapping("/user_work.html")
//	public String user_work(Model model,@CookieValue(value="uid",defaultValue="") String uid,HttpServletRequest request,@RequestParam(defaultValue = "9") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
////		String uid="";
////		String uiiid=uid2;
////		AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
////		if (principal != null) {
////			Map attributes = principal.getAttributes();
////			uid = (String) attributes.get("uid");
////		}
//		if(!StringUtil.isEmpty(uid))
//		{
//			return "you";
//		}
//		else
//		{
//			return "mei";
//		}
//	}
	
	/**
	 * 用户个人创意主页
	 */
	@RequestMapping("/user_work.html")
	public String user_work(Model model, HttpServletRequest request,@RequestParam(defaultValue = "9") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			Integer start = (pageIndex - 1) * pageSize;
			List<CreativeModel> creativeList=creativeService.findCreativeByUid(Integer.parseInt(uid),start, pageSize);
			Integer totalCount = creativeService.countByUid(Integer.parseInt(uid));
			model.addAttribute("creativeList", creativeList);
			model.addAttribute("totalCount", totalCount);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageIndex", pageIndex);
			model.addAttribute("user", userModel);
			return "page-user-work-creative";
		}
	}
	
	@RequestMapping("/other_work_creative.html")
	public String other_work_creative(Model model, @RequestParam("other_uid") Integer other_uid,@RequestParam(defaultValue = "4") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		UserModel other = userService.findUserByUid(other_uid);
		Integer start = (pageIndex - 1) * pageSize;
		List<CreativeModel> creativeList=creativeService.findCreativeByUid(other_uid,start, pageSize);
		Integer totalCount = creativeService.countByUid(other_uid);
		model.addAttribute("creativeList", creativeList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("other", other);
		return "page-other-user-work-creative";
	}
	
	/**
	 * 用户个人剧本主页
	 */
	@RequestMapping("/user_work_script.html")
	public String user_work_script(Model model, HttpServletRequest request,@RequestParam(defaultValue = "4") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			Integer start = (pageIndex - 1) * pageSize;
			List<ScriptModel> scriptList = scriptService.getScriptListByUid(Integer.parseInt(uid),start, pageSize);
			Integer totalCount = scriptService.countByUid(Integer.parseInt(uid));
			model.addAttribute("totalCount", totalCount);
			model.addAttribute("scriptList", scriptList);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageIndex", pageIndex);
			model.addAttribute("user", userModel);
			model.addAttribute("role", userModel.getRole());
			return "page-user-work-script";
		}
	}
	
	@RequestMapping("/user_work_script_attr.html")
	public String user_work_script_attr(Model model, HttpServletRequest request,@RequestParam(defaultValue = "4") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			Integer start = (pageIndex - 1) * pageSize;
			List<ScriptOwnModel> scriptAttributeList = scriptService.getScriptAttributeListByUid(Integer.parseInt(uid),start, pageSize);
			Integer totalCount = scriptService.countAttributeByUid(Integer.parseInt(uid));
			model.addAttribute("totalCount", totalCount);
			model.addAttribute("scriptAttributeList", scriptAttributeList);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageIndex", pageIndex);
			model.addAttribute("user", userModel);
			model.addAttribute("role", userModel.getRole());
			return "page-user-work-script-attr";
		}
	}
	
	/**
	 * 用户个人剧本主页
	 */
	@RequestMapping("/other_work_script.html")
	public String other_work_script(Model model, @RequestParam("other_uid") Integer other_uid,@RequestParam(defaultValue = "4") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		UserModel other = userService.findUserByUid(other_uid);
		Integer start = (pageIndex - 1) * pageSize;
		List<ScriptOwnModel> scriptAttributeList = scriptService.getScriptAttributeListByUid(other_uid,start, pageSize);
		Integer totalCount = scriptService.countAttributeByUid(other_uid);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("scriptAttributeList", scriptAttributeList);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("other", other);
		return "page-other-user-work-script";
	}
	
	/**
	 * 用户个人账户
	 */
	@RequestMapping("/user_account.html")
	public String user_account(Model model,HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
		model.addAttribute("user",userModel);
		return "page-user-account";
	}
	@RequestMapping("/user_cash.html")
	public String user_cash(Model model,HttpServletRequest request, @RequestParam(defaultValue = "15") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		model.asMap().clear();
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		
		Integer user_id = 0;
		try{
			user_id = Integer.parseInt(uid);
		}catch(Exception e){
			user_id = 0;
		}
		List<UserCashLogModel> logList = userCashLogService.getListByUid(user_id, start, pageSize);
		model.addAttribute("logList",logList);
		model.addAttribute("totalCount",userCashLogService.getListCountByUid(user_id));
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("user",userService.findUserByUid(Integer.parseInt(uid)));
		return "page-user-cash";
	}
	@RequestMapping(value = "/user_cash_post.json", method = { RequestMethod.POST })
	public void user_cash_post(Model model,UserCashLogModel cashlog, HttpServletRequest request,  HttpServletResponse response) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			response.getWriter().print("{\"message\":\"请先登录\",\"statusCode\":\"300\"}");
		}
		else
		{
			cashlog.setUid(Integer.parseInt(uid));
			userCashLogService.cashHandle(cashlog);
			response.getWriter().print("{\"message\":\"操作成功\",\"statusCode\":\"200\"}");
		}
	}
	@RequestMapping("/user_balance_check.json")
	public void user_balance_check(Model model,String money, HttpServletRequest request,  HttpServletResponse response) throws Exception {
		response.setContentType("application/json; charset=utf-8");
		String uid = CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid))
		{
			response.getWriter().print("{\"message\":\"请先登录\",\"statusCode\":\"300\"}");
		}
		else    
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			if(Float.parseFloat(money) <= userModel.getBalance()){
				response.getWriter().print("{\"message\":\"操作成功\",\"statusCode\":\"200\"}");
			}else{
				response.getWriter().print("{\"message\":\"余额不足\",\"statusCode\":\"300\"}");
			}
		}
	}
	/**
//	 * 用户交易
//	 */
//	@RequestMapping("/user_trade.html")
//	public String user_trade(Model model, HttpServletRequest request, @RequestParam(defaultValue = "7") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
//		model.asMap().clear();
//		String uid = CasUtil.getUid(request);
//		Integer start = (pageIndex - 1) * pageSize;
//		
//		Integer user_id = 0;
//		try{
//			user_id = Integer.parseInt(uid);
//		}catch(Exception e){
//			user_id = 0;
//		}
//		
//		if(StringUtil.isEmpty(uid))
//		{
//			return "login";
//		}
//		else                                
//		{
//			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
//			List<CreativeOrderModel> orderList = creativeOrderService.getList(user_id, start, pageSize);
//			model.addAttribute("orderList",orderList);
//			model.addAttribute("totalCount",creativeOrderService.getListCount(user_id));
//			model.addAttribute("pageSize", pageSize);
//			model.addAttribute("pageIndex", pageIndex);
//			model.addAttribute("user",userModel);
//			return "page-user-trade";
//		}
//	}
	/**
	 * 用户交易
	 */
	@RequestMapping("/user_trade.html")
	public String user_trade(Integer cid,Model model, HttpServletRequest request, @RequestParam(defaultValue = "7") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		model.asMap().clear();
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		
		Integer user_id = 0;
		try{
			user_id = Integer.parseInt(uid);
		}catch(Exception e){
			user_id = 0;
		}
		
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else                                
		{
			CreativeOrderModel order = new CreativeOrderModel();
			if(cid != null)
			{
				CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
				Long time = new Date().getTime();
				String order_num = time.toString()+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10);
			    order.setOrder_num(order_num);
			    order.setUid(Integer.parseInt(uid));
			    order.setCid(creativeModel.getCid());
			    order.setCuid(creativeModel.getUid());
			    order.setTitle(creativeModel.getTitle());
			    order.setCdescribe(creativeModel.getCdescribe());
			    order.setCvalue(creativeModel.getCvalue());
			    order.setAutro_instr(creativeModel.getAutro_instr());
			    order.setCover_url(creativeModel.getCover_url());
			    order.setSource_url(creativeModel.getSource_url());
			    creativeOrderService.insert(order);
			}
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			List<CreativeOrderModel> orderList = creativeOrderService.getList(user_id, start, pageSize);
			model.addAttribute("orderList",orderList);
			model.addAttribute("totalCount",creativeOrderService.getListCount(user_id));
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageIndex", pageIndex);
			model.addAttribute("user",userModel);
			return "page-user-trade";
		}
	}
	
	@RequestMapping("/user_sell.html")
	public String user_sell(Model model,HttpServletRequest request, @RequestParam(defaultValue = "7") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageIndex) {
		model.asMap().clear();
		String uid = CasUtil.getUid(request);
		Integer start = (pageIndex - 1) * pageSize;
		
		Integer user_id = 0;
		try{
			user_id = Integer.parseInt(uid);
		}catch(Exception e){
			user_id = 0;
		}
		
		if(StringUtil.isEmpty(uid))
		{
			return "login";
		}
		else                                
		{
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			List<CreativeOrderModel> orderList = creativeOrderService.getSellList(user_id, start, pageSize);
			model.addAttribute("orderList",orderList);
			model.addAttribute("totalCount",creativeOrderService.getSellListCount(user_id));
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageIndex", pageIndex);
			model.addAttribute("user",userModel);
			return "page-user-sell";
		}
	}

	
	
	@RequestMapping("index.html")
	public String index(Model model,HttpServletResponse response,HttpServletRequest request) {
		String uid = CasUtil.getUid(request);
		model.addAttribute("uid", uid);
		return "index";
	}

//	@RequestMapping("user_work.html")
//	public String user_work(Model model, Integer uid) {
//		UserModel userModel = userService.findUserByUid(uid);
//		model.addAttribute("userModel", userModel);
//		return "page-user-work";
//	}

	// /**
	// * 用户登陆
	// */
	// @RequestMapping(value = "login.json", method =
	// {RequestMethod.POST,RequestMethod.GET})
	// public void login_post(HttpServletResponse response,Model model,String
	// email, String pwd, HttpSession session) throws IOException {
	// response.setContentType("application/json;charset=UTF-8");
	// Map<String, Object> param = new HashMap<String, Object>();
	// param.put("email", email);
	// param.put("pwd", pwd);
	// UserModel userModel = userService.login(param);
	// if (userModel == null)
	// {
	// response.getWriter().write("{\"success\":\"false\"}");
	// response.getWriter().write("{\"msg\":\"用户名或者密码错误！\"}");
	// }
	// else
	// {
	// Integer uid=userService.findUidByEmail(email);
	// response.getWriter().write("{\"success\":\"true\",\"uid\":\""+uid+"\"}");
	// session.setAttribute("login", true);
	// session.setAttribute("uid",uid);
	// session.setAttribute("email",email);
	// }
	// }

	/**
	 * 用户登陆
	 */
	@RequestMapping(value = "login.json", method = { RequestMethod.POST })
	public void login_post(String email, String pwd, HttpServletResponse response) throws IOException {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("email", email);
		param.put("pwd", MD5.md5(pwd));
		UserModel userModel = userService.login(param);
		if (userModel == null) 
		{
			response.getWriter().write("{\"success\":\"false\",\"msg\":\"用户名或者密码错误！\"}");
		}                              
		else                                
		{
			Integer uid = userModel.getUid();
			String login_time=DateUtil.getCurDateYmd();
			userService.addLoginTime(uid,login_time);
			Cookie cookie = new Cookie("uid", uid.toString());
			cookie.setPath("/");
			response.addCookie(cookie);
			response.getWriter().write("{\"success\":\"true\",\"msg\":\"登录成功!\"}");
		}
	}

	@RequestMapping("account_active.html")
	public String account_active() {
		return "account_active";
	}

	
}